package com.example.day12_7_12_2.util;

import com.example.day12_7_12_2.base.BaseApp;
import com.example.day12_7_12_2.net.WanService;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpUtil {
    private static volatile HttpUtil sHttpUtil = null;
    private Retrofit.Builder mBuilder;

    private HttpUtil(){
        OkHttpClient okHttpClient = initOkHttp();
        initRetrofit(okHttpClient);
    }

    private void initRetrofit(OkHttpClient okHttpClient) {
        mBuilder = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }

    private OkHttpClient initOkHttp() {
        return new OkHttpClient.Builder()
                .addInterceptor(new LogIntercptor())
                .cache(new Cache(new File(BaseApp.sContext.getCacheDir().getAbsolutePath() +
                        File.separator + "data" + "/NetCache"),1024*1024*4))
                .retryOnConnectionFailure(true)
                .build();
    }

    public static HttpUtil getInstance(){
        if (sHttpUtil == null){
            synchronized (HttpUtil.class){
                if (sHttpUtil == null){
                    sHttpUtil = new HttpUtil();
                }
            }
        }
        return sHttpUtil;
    }

    private class LogIntercptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            LogUtil.logD("7-12",response.peekBody(1024*1024).string());
            return response;
        }
    }
    volatile WanService mWanService = null;

    public WanService getWanService(){
        if (mWanService == null){
            synchronized (HttpUtil.class){
                if (mWanService == null){
                    mWanService = mBuilder.baseUrl(WanService.sWanUrl)
                            .build()
                            .create(WanService.class);
                }
            }
        }
        return mWanService;
    }
}
